package util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author tangfudong
 * @date 2020/10/26
 */
@Slf4j
public class ImageUtil {
    /**
     * 下载图片
     */
    public static void loadImg(String urlStr,String dirStr){
        URL url = null;
        try {
            url = new URL(urlStr);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            File dir = new File(dirStr);
            if (!dir.exists()) {
                boolean mkdirs = dir.mkdirs();
                System.out.println("创建文件夹："+mkdirs);
            }
            String fileName = urlStr.substring(urlStr.lastIndexOf("/") + 1);
            FileOutputStream fileOutputStream = new FileOutputStream(new File(dirStr+"\\"+fileName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            //BASE64Encoder encoder = new BASE64Encoder();
            //String encode = encoder.encode(buffer);//返回Base64编码过的字节数组字符串
            //System.out.println(encode);
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            System.out.println("下载图片异常:"+urlStr);
        }
    }
    /**
     * 下载图片
     */
    public static String loadImgEncode(String urlStr){
        URL url = null;
        try {
            url = new URL(urlStr);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            byte[] buffer = new byte[1024];
            int length;
            length = dataInputStream.read(buffer);
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(buffer);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getImageBase64StrFromUrl(String imgSrc) throws Exception{
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try{
            url = new URL(imgSrc);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.setRequestMethod("GET");
            httpUrl.setConnectTimeout(30 * 1000);
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[2048];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return java.util.Base64.getEncoder().encodeToString(outStream.toByteArray());
        }catch (Exception e) {
            throw new Exception(e);
        }finally{
            if(is != null) {
                try {is.close(); } catch (IOException e) {e.printStackTrace(); }
            }
            if(outStream != null) {
                try {outStream.close();} catch (IOException e) {e.printStackTrace();}
            }
            if(httpUrl != null){ httpUrl.disconnect();}
        }
    }

    /**
     *  根据地址获得数据的字节流 - GET请求
     * @param strUrl
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) throws Exception {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);
            // 通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            // 得到图片的二进制数据
            byte[] btImg = readInputStream(inStream);
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
            throw  new Exception(e.getMessage());
        }
    }

    /**
     * @Function: 从输入流中获取数据
     * @param inStream - 输入流
     * @throws IOException
     */
    private static byte[] readInputStream(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}
